package com.xiaowu.xblog.web;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import io.swagger.v3.oas.annotations.Operation;
import jakarta.servlet.http.HttpServletResponse;
import lombok.AllArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @description:
 * @author: xiaowu
 * @time: 2025/6/25 13:09
 */

@RestController
@RequestMapping("/common")
@AllArgsConstructor
public class CommonController {

    private final StringRedisTemplate redisTemplate;

    @Operation(summary = "获图形验证码接口")
    @GetMapping("/captcha")
    public void generateCaptcha(HttpServletResponse response) throws Exception {
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(100, 40, 4, 40);
        String code = lineCaptcha.getCode();
        String captchaCode = UUID.randomUUID().toString();

        redisTemplate.opsForValue().set("captcha:" + captchaCode, code, 3, TimeUnit.MINUTES);

        // 明确设置响应头（两种方式都加上）
        response.setHeader("Captcha-Code", captchaCode);
        response.addHeader("Access-Control-Expose-Headers", "Captcha-Code"); // 关键！

        response.setContentType("image/png");
        lineCaptcha.write(response.getOutputStream());
    }
}
